/**
 * IdleConnectionMonitorThread.java<br>
 *
 * @author aaronwong.sd@foxmail.com
 * @version 下午3:07:10
 */
package com.mc.httpclient;

import java.util.concurrent.TimeUnit;

import org.apache.http.conn.HttpClientConnectionManager;

import com.mc.util.PropertyUtils;

/**
 * 超时链接管理
 *
 * @author aaronwong.sd@foxmail.com
 */
public class IdleConnectionMonitorThread extends Thread {

	private final HttpClientConnectionManager	connMgr;
	private volatile boolean					shutdown;
	private int									idleTime;

	public IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
		this.connMgr = connMgr;
		PropertyUtils config = PropertyUtils.getInstance();
		this.idleTime = config.getIntValue("httpclient", "connection.idle.time");
		if (this.idleTime < 30) {
			this.idleTime = 30;
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		try {
			while (!this.shutdown) {
				synchronized (this) {
					this.wait(5000);
					// 关闭失效的连接
					this.connMgr.closeExpiredConnections();
					// 可选的, 关闭idleTime秒内不活动的连接
					this.connMgr.closeIdleConnections(this.idleTime, TimeUnit.SECONDS);
				}
			}
		} catch (InterruptedException ex) {
			// terminate
		}
	}

	public void shutdown() {
		this.shutdown = true;
		synchronized (this) {
			this.notifyAll();
		}
	}
}
